package com.vcom.deploy.cmd;

import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;

import java.util.stream.Collectors;
import java.util.stream.Stream;


@Controller
@Mapping("/cmd")
public class CmdController {

    @Inject
    private CmdService cmdService;

    @Mapping("/ll")
    public String ll(String dir) {
        String cmd = "ls -alh " + dir;
        System.out.println(cmd);
        return cmdService.executeCmd(cmd);
    }

    @Mapping("/ps")
    public String ps(String keyWords) {
        String cmd = "ps -aux";
        System.out.println(cmd);
        String s = cmdService.executeCmd(cmd);
        return Stream.of(s.split("\n"))
                .filter(w -> w.contains(keyWords) || w.contains("%CPU"))
                .collect(Collectors.joining("\n"));
    }

    @Mapping("/cmd")
    public String cmd(String cmd) {
        System.out.println(cmd);
        return cmdService.executeCmd(cmd);
    }

    @Mapping("/rm")
    public String rm(String match) {
        String cmd = "rm -rf " + match;
        System.out.println(cmd);
        return cmdService.executeCmd(cmd);
    }

    @Mapping("/sh")
    public String sh(String shellFilePath) {
        String cmd = "sh " + shellFilePath;
        System.out.println(cmd);
        return cmdService.executeCmd(cmd);
    }

    @Mapping("/cat")
    public String cat(String filePath) {
        String cmd = "cat " + filePath;
        System.out.println(cmd);
        return cmdService.executeCmd(cmd);
    }
}
